import Vue from 'vue';
import VueRouter from 'vue-router';
import store from "@/store";

Vue.use(VueRouter);
import routes from './routes';
//先把VueRouter原型对象的push/replace先保存一份
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;
//重写push|replace方法
// 1.location传递的哪些参数，告诉原来的push，往哪里跳转 2.resolve:成功回调， 3.失败回调
VueRouter.prototype.push = function (location, resolve, reject) {
    if (resolve && reject) {
        //call||apply区别：相同点都可以调用函数，都可以篡改函数this上下文
        //不同点：传递参数的不同，call传递参数用逗号隔开，apply数组
        originPush.call(this, location, resolve, reject)
    } else {
        originPush.call(this, location, () => { }, () => { })
    }
};
VueRouter.prototype.replace = function (location, resolve, reject) {
    if (resolve && reject) {
        //call||apply区别：相同点都可以调用函数，都可以篡改函数this上下文
        //不同点：传递参数的不同，call传递参数用逗号隔开，apply数组
        originReplace.call(this, location, resolve, reject)
    } else {
        originReplace.call(this, location, () => { }, () => { })
    }
};


let router = new VueRouter({
    routes,
    scrollBehavior(to, from, savedPosition) {
        //y等于零代表滚动条在最上方
        return { y: 0 }
    }
})
//全局守卫:前置守卫
router.beforeEach(async (to, from, next) => {
    //next()放行函数
    //用户登录，才会生成token,未登录一定不会有token
    let token = store.state.user.token;
    let name = store.state.user.userInfo.name;
    if (token) {
        next();
        //用户登录就不允许去login
        if (to.path == '/login' || to.path == '/register') {
            alert('已登录，无需重复操作')
            next('/home');
        } else {
            //登录了，但是去的不是login
            //如果用户名已有
            if (name) {
                next();
            } else {
                try {
                    //没有用户信息，派发action让仓库存储用户信息在跳转
                    //获取用户信息在首页展示
                    await store.dispatch('getUserInfo');
                } catch (err) {
                    //token失效,获取不到用户信息
                    //清除token
                    await store.dispatch('userLogout');
                    next('/login');
                }
            }
        }
    } else {
        //未登录:不能交易
        let toPath = to.path;
        if (toPath.indexOf('/trade')!=-1 || toPath.indexOf('/pay')!=-1 || toPath.indexOf('/center')!=-1) {
            alert('您还未登录,请先登录');
            next('/login?redirect='+toPath);
        } else {
            next();
        }
    }
})
export default router;